<template>
  <div class="submission">
    <ylheader
      :lefttext="true"
      @save="saveArticles(1)"
      @send="saveArticles(0)"
      :lefttexts="'取消'"
      :title="mytitle"
      :righttext="true"
      :righttexts="'发送'"
    ></ylheader>

    <versioncofig
      :versionTitle="articlesConfig.title"
      @toVersionDetail="$router.push({name:'activityrule',query:{tag:8}, params:{articlesContent:articlesConfig.content}})"
      @canclVersion="isRuleShow=!isRuleShow"
      v-if="isRuleShow"
    ></versioncofig>

    <div :style="{'margin-top':isRuleShow?'0.6rem':'0'}">
      <input
        type="text"
        v-model="articleTitle"
        placeholder="请输入标题"
        class="article-title one-line"
        maxlength="25"
      >
      <quill-editor
        ref="myTextEditor"
        v-model="content"
        :options="editorOption"
        @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
        @ready="onEditorReady($event)"
      ></quill-editor>
      <input
        id="uniqueId"
        multiple="multiple"
        type="file"
        accept="image/gif, image/jpeg, image/png, image/jpg"
        class="myinput"
        @change="createImage($event)"
      >
    </div>
  </div>
</template>

<script>
import ylheader from "src/components/yl-header.vue";
import axios from "axios";
import { Indicator } from "mint-ui";
import versioncofig from "src/components/common/versionconfig.vue";
import api from "src/api/index";
// require styles
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor, Quill } from "vue-quill-editor";
import ImageResize from "quill-image-resize-module";
Quill.register("modules/imageResize", ImageResize);

export default {
  name: "submission",
  components: { ylheader, quillEditor, Indicator, versioncofig },
  data() {
    return {
      mytitle: "投稿话题",
      content: "",
      token: "",
      isRuleShow: true,
      articleTitle: "",
      articlesConfig: {},
      draftId: "",
      editorOption: {
        modules: {
          imageResize: {},
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ indent: "-1" }, { indent: "+1" }],
            [{ color: [] }, { background: [] }],
            [{ align: [] }],
            ["image"]
          ],
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      }
    };
  },

  computed: {
    editor() {
      return this.$refs.myTextEditor.quill;
    },
    contentCode() {
      return hljs.highlightAuto(this.content).value;
    }
  },

  watch: {},

  created() {},

  mounted() {
    this.queryArticlesDraft();
    this.getqiuniutoken();
    this.addImageUploadClick();
    this.queryArticlesConfig();
    this.editor.root.dataset.placeholder = "请输入内容";
    var limit = 100;
    var that = this;
    this.editor.on("text-change", function(delta, old, source) {
      if (that.editor.getLength() < limit) {
        that.editor.deleteText(limit, that.editor.getLength());
      }
    });
  },
  methods: {
    saveArticles(draft) {
      //draft--是否是草稿，0否1是
      if (draft == 0) {
        if (this.articleTitle == "") {
          this.$toast("标题不能为空");
          return;
        }
        if (this.editor.container.firstChild.innerHTML == "<p><br></p>") {
          this.$toast("内容不能为空");
          return;
        }
        if (this.editor.getLength()<100) {
          this.$toast("投稿内容必须100字以上");
          return;
        }
      }
      const params = {
        token: localStorage.getItem("token"),
        draft: draft,
        title: this.articleTitle,
        content: this.editor.container.firstChild.innerHTML
      };
      if (this.draftId != "") {
        params.id = this.draftId;
      }

      api.saveArticles(params).then(res => {
        if (res.code == 0) {
          if (draft == 0) {
            this.$toast("投稿成功，您可在我的-我的投稿中查看");
            let that = this;
            setTimeout(() => {
              that.$router.go(-1);
            }, 500);
          } else {
            this.$router.go(-1);
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    addImageUploadClick() {
      let vm = this;
      let imgHandler = async function(image) {
        vm.addImgRange = vm.editor.getSelection();
        if (image) {
          const fileInput = document.getElementById("uniqueId"); //隐藏的file文本ID
          fileInput.click(); //加一个触发事件
        }
      };
      vm.editor.getModule("toolbar").addHandler("image", imgHandler);
    },
    onEditorBlur(editor) {
      console.log("editor blur!", editor);
    },
    onEditorFocus(editor) {
      console.log("editor focus!", editor);
    },
    onEditorReady(editor) {
      console.log("editor ready!", editor);
    },
    queryArticlesConfig() {
      api.queryArticlesConfig().then(res => {
        if (res.code == 0) {
          this.articlesConfig = res.data;
          if (res.data) {
            this.isRuleShow = true;
          } else {
            this.isRuleShow = false;
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    //查询草稿
    queryArticlesDraft() {
      api.queryArticlesDraft().then(res => {
        if (res.code == 0) {
          if (res.articles) {
            this.draftId = res.articles.id;
            this.articleTitle = res.articles.title;
            this.editor.container.firstChild.innerHTML = res.articles.content;
          }
        } else {
          this.$toast(res.msg);
        }
      });
    },
    createImage(event) {
      let file = event.target.files;
      let that = this;
      _each(file, (v, i) => {
        //判断图片上传类型
        var tempIndex = v.type.lastIndexOf("/");
        var imgType = v.type.substring(tempIndex + 1);
        if (
          imgType !== "jpg" &&
          imgType !== "jpeg" &&
          imgType !== "png" &&
          imgType !== "gif"
        ) {
          that.$toast("不支持的图片类型");
          return;
        }
        Indicator.open("上传中...");
        //100k以上压缩
        if (v.size < 102400) {
          that.upload(v);
        } else {
          that.isupload = true;
          lrz(v, { quality: 0.8 })
            .then(function(rst) {
              v = rst.file;
              that.upload(v);
              return rst;
            })
            .catch(function(err) {
              // 处理失败会执行
              Indicator.close();
              console.log(err);
            })
            .always(function() {
              // 不管是成功失败，都会执行
            });
        }
      });
    },
    upload(v) {
      const self = this;
      const fd = new window.FormData();
      fd.append("token", this.token);
      fd.append("file", v);
      axios
        .post("https://upload-z2.qiniup.com", fd, {
          headers: {
            "Content-Type": "multipart/form-data",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers":
              "Origin, X-Requested-With, Content-Type, Accept"
          },
          timeout: 40000
        })
        .catch(error => {
          this.isupload = false;
          this.$toast("图片上传超时!!");
          Indicator.close();
        })
        .then(res => {
          Indicator.close();
          const url = "https://youlingqinius.wonderlandnet.cn/" + res.data.key;
          if (url != null && url.length > 0) {
            // 将文件上传后的URL地址插入到编辑器文本中
            let vm = this;
            let value = url;
            // API: https://segmentfault.com/q/1010000008951906
            // this.$refs.myTextEditor.quillEditor.getSelection();
            // 获取光标位置对象，里面有两个属性，一个是index 还有 一个length，这里要用range.index，即当前光标之前的内容长度，然后再利用 insertEmbed(length, 'image', imageUrl)，插入图片即可。
            vm.addRange = vm.editor.getSelection();
            vm.editor.insertEmbed(
              vm.addRange !== null ? vm.addRange.index : 0,
              "image",
              value,
              Quill.sources.USER
            ); // 调用编辑器的 insertEmbed 方法，插入URL
          } else {
            this.$toast(`插入失败`);
          }
        });
    },
    getqiuniutoken() {
      api
        .Queryuploadtoken({})
        .then(res => {
          if (res.success) {
            this.token = res.token;
          }
        })
        .catch(error => {});
    }
  }
};
</script>

<style lang="less" scoped>
.myinput {
  display: none;
}
</style>
<style lang="less">
.submission {
  .article-title {
    height: 0.8rem;
    margin: 0 0.3rem;
    background: #f5f5f5;
    width: 92%;
    border-bottom: 1px solid #e6e6e6;
    font-size: 0.34rem;
    color: #999999;
  }
  .shuo-rule {
    top: 0.88rem;
  }
  .ql-container {
    min-height: 300px;
    .ql-editor {
      border-top: 1px solid #e6e6e6;
      padding: 12px 0;
      margin: 0 0.3rem;
    }
  }
  .ql-container.ql-snow {
    border: none;
  }
  .ql-toolbar.ql-snow {
    border: none;
  }
}
</style>


